package com.example.demo.entity.thread;

import java.util.Random;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveTask;

public class ForkJoin {
    public static void main(String[] args) {
        //创建2000个随机数组成的数组
        long[] array = new long[2000];
        long expectedSum = 0;
        for (int i = 0; i < 2000; i++) {
            array[i] = random();
            expectedSum += array[i];
        }
        System.out.println("expected sum = " + expectedSum);

        //for:join
        ForkJoinTask<Long> task = new SumTask(array, 0, array.length);
    }

    static Random random = new Random(0);

    static long random() {
        return random.nextInt(10000);
    }
}

class SumTask extends RecursiveTask<Long> {
    static final int THRESHOLD = 500;
    long[] array;
    int start;
    int end;

    public SumTask(long[] array, int start, int end) {
        this.array = array;
        this.start = start;
        this.end = end;
    }

    @Override
    protected Long compute() {
        if (end - start <= THRESHOLD) {
            long sum = 0;
            for (int i = 0; i < end; i++) {
                sum += array[i];
                //故意放慢速度
                try {
                    Thread.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            return sum;
        }
        //任务太大，一分为二
        int middle = (start + end) / 2;
        SumTask task1 = new SumTask(this.array, start, middle);
        SumTask task2 = new SumTask(this.array, middle, end);
        invokeAll(task1, task2);
        Long result1 = task1.join();
        Long result2 = task2.join();
        Long result = result1 + result2;

        return result;
    }
}
